import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io' as io;
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:super_tool_server/business/log_manager.dart';
import 'package:super_tool_server/common/utils/log.dart';
import 'package:super_tool_server/model/message_info.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:path_provider/path_provider.dart';

class WebsocketManager {
  // late BehaviorSubject<AutoTestStatusInfo> _subject;

  WebsocketManager._() {
    // _subject = BehaviorSubject<AutoTestStatusInfo>();
  }

  static WebsocketManager? _instance;

  // Stream<AutoTestStatusInfo> get stream => _subject.stream;

  static WebsocketManager getInstance() {
    if (_instance == null) {
      _instance = WebsocketManager._();
    }
    return _instance!;
  }

  void dispose() {
    // _subject.close();
  }

  WebSocketChannel? ueChannel;

  void handleMsg(WebSocketChannel webSocket, MessageInfo messageInfo) {
    LogManager.getInstance()
        .addLog('${DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now())} 收到\n$messageInfo', color: Colors.green);
    if (messageInfo.cmdType == 'CLIENT_TYPE') {
      if (messageInfo.param == 'UE') {
        ueChannel = webSocket;
      }
    } else if (messageInfo.cmdType == 'UE_CONTROL') {
      if (ueChannel != null) {
        ueChannel!.sink.add(messageInfo.param);
        superLog.info('sendMsgToUE: ${messageInfo.param}');
      } else {
        superLog.info('UE 未连接');
      }
    } else {
      superLog.warning('消息类型不支持: $messageInfo');
    }
  }

  void sendMsgToUE(MessageInfo msg) {
    if (ueChannel != null) {
      ueChannel!.sink.add(msg.toString());
      superLog.info('sendMsgToUE: $msg');
    }
  }

  Future<SecurityContext> _loadSecurityContext() async {
    // 1. 从 asset 读取证书和私钥内容
    final certData = await rootBundle.load('assets/certs/127.0.0.1+2.pem');
    final keyData = await rootBundle.load('assets/certs/127.0.0.1+2-key.pem');

    // 2. 获取临时目录
    final tempDir = await getTemporaryDirectory();
    superLog.info('tempDir=${tempDir.path}');

    // 3. 写入临时文件
    final certFile = File('${tempDir.path}/server_cert.pem');
    final keyFile = File('${tempDir.path}/server_key.pem');

    await certFile.writeAsBytes(certData.buffer.asUint8List());
    await keyFile.writeAsBytes(keyData.buffer.asUint8List());

    // 4. 创建 SecurityContext
    final context = SecurityContext()
      ..useCertificateChain(certFile.path)
      ..usePrivateKey(keyFile.path);

    return context;
  }

  Future<void> startServer() async {
    var handler = webSocketHandler((WebSocketChannel webSocket) {
      webSocket.stream.listen((message) {
        superLog.info('收到: $message');
        try {
          MessageInfo messageInfo = MessageInfo.fromJson(json.decode(message));
          superLog.info('解析消息成功: $messageInfo');
          handleMsg(webSocket, messageInfo);
        } catch (e, trace) {
          superLog.severe("消息解析失败 $e\n$trace");
        }
      });
    });
    if (Platform.isWindows) {
      shelf_io.serve(handler, '127.0.0.1', 8866).then((server) {
        String info = 'Serving at ws://${server.address.host}:${server.port}';
        superLog.info(info);
        LogManager.getInstance()
            .addLog('${DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now())} $info', color: Colors.green);
      });
    } else {
      // 🔐 加载证书和私钥
      final securityContext = await _loadSecurityContext();
      shelf_io.serve(handler, '127.0.0.1', 8866, securityContext: securityContext).then((server) {
        String info = 'Serving at wss://${server.address.host}:${server.port}';
        superLog.info(info);
        LogManager.getInstance()
            .addLog('${DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now())} $info', color: Colors.green);
      });
    }
  }
}
